package fms.core;

import fms.acarsMsgProcessUtil.DownLinkDatagramHeader;
import fms.acarsMsgProcessUtil.RawDatagram;
import fms.util.DateUtil;
import fms.util.StringUtil;
import fms.util.SysConstants;
import fms.webservice.Request;
import fms.xml.WindRequestXML;
import fms.webservice.XmlUtil;
import org.apache.log4j.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownRequestWind {
    private Logger logger = Logger.getLogger(DownRequestWind.class);

    private final String regexRequestWind = "[\\s\\S]*?/WQ([\\s\\S]*?):([\\s\\S]*?)/[\\s\\S]*?";

    public Request parse(String aContent) {
        // POS报无下行请求包
        logger.info("收到风温请求下行报：\r\n" + aContent);
        logger.debug("[报文解析] 开始进行‘风温请求’报文解析...");
        Request reqWind = new Request();
        reqWind.setServiceType( String.valueOf( ServiceType.WindRequest.ordinal() ) );
        reqWind.setVersion("1.0");
        WindRequestXML reqWindXml = new WindRequestXML();

        DownLinkDatagramHeader msgHeader = null;
        String freeText = "";
        try {
        // 获取自由文（最后可能尾部包含空格，要小心)
            freeText = RawDatagram.GetBody(aContent);
            logger.info("DownRequestWind:parse 获取正文成功：" + freeText);
//        System.out.println(":::::::" + freeText + "::::");
//        String rawMsg = "REQPWI/CQ351/WQ351:ALDAP.IBEGI.ODULO.GORPI.SAGUT.IDVEL.XDX.TAO.XIVID.FD.TEKAM.IGDEG.NIXEP.TANIB.MAKNO.UDETI.VENOS.CHI.NODAL.ISKEM.BIDIB.NUBKI.LEMOT.LJB.ZYCC/DQ351/WRZYCC.ZYTXA130";
//        System.out.println(":::::::" + rawMsg + "::::");
            msgHeader = DownLinkDatagramHeader.Parse(RawDatagram.GetHeader(aContent));
            logger.debug("解析报头成功！");
        } catch (Exception e) {
            logger.error(e.getMessage() + "解析报头失败：\r\n" + aContent);
            return null;
        }

        Pattern pattern = Pattern.compile(regexRequestWind);
        Matcher matcher = pattern.matcher(freeText.trim()); // rawMsg
        if (matcher.matches()) {
            logger.debug("开始填充RequsetWindXml！");

            String reqAlts = matcher.group(1);
            String reqCptNames = matcher.group(2);

            // 去重重复高度层，且要保证原有的高度层请求顺序（为了使回复报文按请求顺序组报）
            reqAlts = StringUtil.removeRepeat( reqAlts.split("\\."), "." );
            reqWindXml.setAlt(reqAlts);
            reqWindXml.setCptname(reqCptNames);

            // webservice中将航班号中的公司二字码和数字拆开查询
            reqWindXml.setAircraftid(msgHeader.getAn());
            reqWindXml.setFlightID(msgHeader.getFi().toString());

            // webservice风温请求要求“请求时间”字段必填
            reqWindXml.setRequestdate(DateUtil.getCurUTCtime(SysConstants.FORMAT_DATETIME_FULL));

//            reqWindXml.setAlt("39000");
//            reqWindXml.setCptname("TAO  ");
//            reqWindXml.setAircraftid("B-6619");
//            reqWindXml.setFlightID("NO1161");
//            reqWindXml.setRequestdate("2014-05-20 00:00:00");
//            reqWindXml.setUsername("admin");
//            reqWindXml.setPassword("password");
        } else {
            logger.error("风温请求信息解析失败，原始报文为：" + aContent);
            return null;
        }
        reqWind.setRequestXML( XmlUtil.marshallWindRequest(reqWindXml) );
		return reqWind;
	}


}